package com.ruoyi.recycle.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.core.web.controller.BaseController;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.recycle.domain.AdminAddress;
import com.ruoyi.recycle.domain.AdminAddressConfig;
import com.ruoyi.recycle.dto.AdminAddressDto;
import com.ruoyi.recycle.dto.TestDtoOne;
import com.ruoyi.recycle.service.AdminAddressConfigService;
import com.ruoyi.recycle.service.AdminAddressService;
import com.ruoyi.recycle.service.UniversalService;
import com.ruoyi.recycle.utils.OssUpload;
import io.swagger.annotations.*;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/universal")
@Api(tags = "通用信息")
public class UniversalController extends BaseController {

    @Resource
    private UniversalService universalService;
    @Resource
    private AdminAddressService adminAddressService;
    @Resource
    private AdminAddressConfigService adminAddressConfigService;


    @PostMapping("/exportImport")
    @ApiOperation(value = "图片上传")
    @ApiResponses({
            @ApiResponse(code = 200, message = "失败抛出异常"),
    })
    @ApiImplicitParam(name = "file", dataType = "MultipartFile")
    public R exportImport(@RequestParam("file") MultipartFile file) {
        try {
            String sux = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
            String s = OssUpload.uploadFile(file, sux);
            return R.ok(s);
        } catch (Exception ex) {
            return R.fail("图片上传失败！");
        }
    }

    /**
     * 首页统计数据接口
     */
    @GetMapping("/homePageStatisticalData")
    @ApiOperation(value = "首页统计数据接口")
    public AjaxResult homePageStatisticalData() {

        return universalService.homePageStatisticalData();
    }

    /**
     * 首页统计用户轨迹
     * stateTime  时间  当type = 3时不允许为空
     * type       0当天，1昨天，2最近7天，3 从stateTime至今 默认传个15天
     */
    @GetMapping("/homePageStatisticalClientData")
    @ApiOperation(value = "首页统计用户轨迹")
    @ApiImplicitParams({@ApiImplicitParam(name = "stateTime", value = "时间（yyyy-mm-dd）", dataType = "Date", example = "当type = 3时不允许为空"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", example = "0当天，1昨天，2最近7天，3 从stateTime至今 默认传个15天")})
    public AjaxResult homePageStatisticalClientData(@RequestParam(value = "stateTime", required = false) Date stateTime, @RequestParam("type") String type) {

        return universalService.homePageStatisticalClientData(stateTime, type);
    }


    /**
     * 首页统计用户轨迹(地图使用)
     * stateTime  时间  当type = 3时不允许为空
     * type       0当天，1昨天，2最近7天，3 从stateTime至今 默认传个15天
     */
    @GetMapping("/mapTrajectoryStatistics")
    @ApiOperation(value = "首页统计用户轨迹(地图使用)")
    @ApiImplicitParams({@ApiImplicitParam(name = "stateTime", value = "时间（yyyy-mm-dd）", dataType = "Date", example = "当type = 3时不允许为空"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", example = "0当天，1昨天，2最近7天，3 从stateTime至今 默认传个15天")})
    public AjaxResult mapTrajectoryStatistics(@RequestParam(value = "stateTime", required = false) Date stateTime, @RequestParam("type") String type) {

        return universalService.mapTrajectoryStatistics(stateTime, type);
    }

    /**
     * 导库使用-导入省市区
     */
    @PostMapping("/importDataAddress")
    public AjaxResult importDataAddress(@RequestBody List<TestDtoOne> TestDtoOnes) {
        return universalService.test(TestDtoOnes);
    }

    /**
     * 首页统计积分订单数据
     * stateTime  时间  当type = 3时不允许为空
     * type       0当天，1昨天，2最近7天，3 从stateTime至今 默认传个15天
     */
    @GetMapping("/homePageStatisticalIntegralOrderData")
    @ApiOperation(value = "首页统计积分订单数据")
    @ApiImplicitParams({@ApiImplicitParam(name = "stateTime", value = "时间（yyyy-mm-dd）", dataType = "Date", example = "当type = 3时不允许为空"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", example = "0当天，1昨天，2最近7天，3 指定某一天")})
    public AjaxResult homePageStatisticalIntegralOrderData(@RequestParam(value = "stateTime", required = false) Date stateTime, @RequestParam(value = "type", required = true) String type) {

        return universalService.homePageStatisticalIntegralOrderData(stateTime, type);
    }


    /**
     * 首页统计回收订单
     * stateTime  时间  当type = 3时不允许为空
     * type       0当天，1昨天，2最近7天，3 从stateTime至今 默认传个15天
     */
    @GetMapping("/homePageStatisticalRecycleOrderData")
    @ApiOperation(value = "首页统计回收订单")
    @ApiImplicitParams({@ApiImplicitParam(name = "stateTime", value = "时间（yyyy-mm-dd）", dataType = "Date", example = "当type = 3时不允许为空"),
            @ApiImplicitParam(name = "type", value = "类型", dataType = "String", example = "0当天，1昨天，2最近7天，3 指定某一天")})
    public AjaxResult homePageStatisticalRecycleOrderData(@RequestParam(value = "stateTime", required = false) Date stateTime, @RequestParam(value = "type", required = true) String type) {

        return universalService.homePageStatisticalRecycleOrderData(stateTime, type);
    }


    /**
     * 获取当前快递收件地址
     */
    @GetMapping("/getAdminAddress")
    @ApiOperation(value = "设置快递收件地址")
    public AjaxResult getAdminAddress() {
        return adminAddressService.getAdminAddress();
    }

    /**
     * 根据ID获取快递收件地址
     */
    @GetMapping("/getAdminAddressById/{id}")
    @ApiOperation(value = "根据快递地址ID获取快递地址")
    public AjaxResult getAdminAddressById(@PathVariable("id") Long id) {
        return AjaxResult.
                success("adminAddress",adminAddressService.getById(id)).
                put("adminAddressConfig",adminAddressConfigService.list(new LambdaQueryWrapper<AdminAddressConfig>().eq(AdminAddressConfig::getAdminAddressId,id)));
    }

    /**
     * 设置快递收件地址
     */
    @PostMapping("/updateAdminAddress")
    @ApiOperation(value = "设置快递收件地址")
    public AjaxResult updateAdminAddress(@RequestBody AdminAddressDto adminAddressDto) {
        return adminAddressService.updateAdminAddress(adminAddressDto);
    }

    /**
     * 设置快递收件地址
     */
    @GetMapping("/deleteAdminAddress/{id}")
    @ApiOperation(value = "设置快递收件地址")
    public AjaxResult deleteAdminAddress(@PathVariable("id") Long id) {
        adminAddressService.removeAdminAddress(id);
        return AjaxResult.success();
    }

    /**
     * 设置发货快递
     */
    @PostMapping("/setExpress")
    @ApiOperation(value = "设置发货快递")
    public AjaxResult setExpress(@RequestParam(value = "express", required = false) String express,
                                 @RequestParam(value = "addressId", required = false) Long addressId) {
        return adminAddressService.setExpress(express,addressId);
    }

    /**
     * 获取可用快递公司与当前所选快递公司
     */
    @GetMapping("/getExpress")
    @ApiOperation(value = "获取可用快递公司与当前所选快递公司")
    public AjaxResult getExpress() {
        return adminAddressService.getExpress();
    }


    /**
     * 获取地址的经纬度
     */
    @GetMapping("/addressApi")
    public AjaxResult addressApi(@RequestParam(value = "address") String address) {

        if (StringUtils.isBlank(address)) {
            return AjaxResult.error("请输入地址");
        }
        try {
            CloseableHttpClient httpClient = HttpClients.createDefault();

            String httpUrl = "http://api.map.baidu.com/geocoding/v3/?output=json&location=showLocation&ak=RAFP4WWoO1f7XHznlZjibhzUBxGfYYGT&address=" + address;
            // 创建默认http连接
            HttpGet httpGet = new HttpGet(httpUrl);

            CloseableHttpResponse response = httpClient.execute(httpGet);

            HttpEntity httpEntity = response.getEntity();

            String json = EntityUtils.toString(httpEntity);

            Map<String, Object> result = JSONObject.parseObject(json, Map.class);
            // JSON转对象
            return AjaxResult.success(result);
        } catch (Exception e) {
            logger.error("地理编码[异常],", e);
            return AjaxResult.error("获取地理编码[异常]");
        }
    }


}
